package com.ymk.cmd;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ymk.base.cmd.ACmd;
import com.ymk.base.cmd.CmdSign;
import com.ymk.base.exception.MallException;
import com.ymk.base.utlis.DateUtil;
import com.ymk.base.utlis.ParamsBuilder;
import com.ymk.bo.user.UserInfoBO;
import com.ymk.core.code.cmd.UserCmdCode;
import com.ymk.core.constants.MemberConstants;
import com.ymk.core.constants.WxConstants;
import com.ymk.service.IUserInfoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * 抖音小程序登录
 */
@Service
public class UserLogin extends ACmd {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private IUserInfoService userService;


    @Override
    public CmdSign executeSop(HttpServletRequest request, CmdSign sign) throws Exception {
        CmdSign respSign = new CmdSign(sign);
        UserInfoBO reqData = super.getData(sign, UserInfoBO.class);

        ParamsBuilder params = ParamsBuilder.newBuild()
                .addParam("appid", WxConstants.DY_APP_ID)
                .addParam("secret", WxConstants.DY_APP_SECRET)
                .addParam("code", reqData.getReqCode());
       // 发送登录请求
       String result =  restTemplate.exchange(WxConstants.DY_LOGIN_URL, HttpMethod.POST, new HttpEntity<>(params.build(), null), String.class).getBody();
       JSONObject param = JSON.parseObject(result);
       if ((int)param.get("err_no") != 0){
           throw new MallException("登录异常："+param.getString("err_tips"));
       }
       String openId = param.getJSONObject("data").getString("openid");
       String sessionKey = param.getJSONObject("data").getString("session_key");
        ParamsBuilder paramsBuilder = ParamsBuilder.newBuild()
                .addParam("wxOpenId", openId)
                .setReturnStruct(sign.getReturnStruct());
        UserInfoBO respData = this.userService.get(paramsBuilder.build());

        if (!Objects.isNull(respData)) {
            respData.setSessionKey(sessionKey);
            this.userService.update(respData);
            respSign.setSource(super.getSource(respData));
        } else {
            respData = new UserInfoBO();
            respData.setWxOpenId(openId);
            respData.setUserId(DateUtil.getDateUUid());
            respData.setName(MemberConstants.DY_MEMBER_DEFAULT_NAME);
            respData.setSessionKey(sessionKey);
            this.setCreatedData(respSign, respData);
            this.userService.post(respData);
            respSign.setSource(super.getSource(respData));
        }

        return respSign;

    }

    @Override
    public CmdSign verify(HttpServletRequest request, CmdSign sign) throws Exception {
        UserInfoBO reqData = super.getData(sign, UserInfoBO.class);

        if (StringUtils.isBlank(reqData.getReqCode())) {
            throw new MallException("请求code不能为空");
        }

        return null;
    }

    /**
     * 命令编号
     *
     * @return
     */
    @Override
    public String getCmdCode() {
        return UserCmdCode.USER_LOGIN;
    }

}
